package com.liumin.comlink.http.response;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * 请求失败，返回数据格式与正确返回数据格式不一样的处理
 * 2019/12/25 10:28
 *
 * @author LiuWeiHao
 */
public class HttpGsonConverFactory extends Converter.Factory {
    private final Gson gson;

    private HttpGsonConverFactory(Gson gson) {
        if (gson == null) {
            throw new NullPointerException("gson == null");
        }
        this.gson = gson;
    }

    public static HttpGsonConverFactory create() {
        return create(new Gson());
    }

    public static HttpGsonConverFactory create(Gson gson) {
        return new HttpGsonConverFactory(gson);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new HttpGsonResponseBodyConverter<>(gson, adapter);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new HttpGsonRequestbodyConverter<>(gson, adapter);
    }
}
